﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using PPI.Client;
using PPI.Client.Logic.Distribution;
using PPI.Client.Utils;
using PPI.Entities.Distribution;
using PPI.Entities.Enumerator;
using PPI.Entities.XML;
using PPI.General;

namespace PPI.CRUD
{
    public partial class frmDistributionMeterEditor : frmBase
    {
        public EMeter Meter {get; set;}
        public EDistributionPole Pole { get; set; }
        public EXmlOutboxBase m_OutboxBase { get; set; }

        public frmDistributionMeterEditor()
        {
            InitializeComponent();
        }

        public void LoadControls()
        {
            lstNotes.DataSource = LCacheDistributionDataSingleton.Instance.MeterNotes;

            if (m_OutboxBase.DatabaseType == DatabaseTypes.DistributionGPS) 
            {
                lblComments.Visible = false;
                txtComments.Visible = false;
            }
        }

        public void LoadMeter()
        {
            txtComments.Text = Meter.Comments;
            txtNumber.Text = Meter.Number;
            position1.SetLatitude(Meter.Latitude == double.MinValue ? 0 : Meter.Latitude);
            position1.SetLongitude(Meter.Longitude == double.MinValue ? 0 : Meter.Longitude);
            
            lstNotes.ClearSelected();
            foreach (ENote note in Meter.Notes) 
                for (int i = 0; i < lstNotes.Items.Count; i++) 
                    if (((ENote)lstNotes.Items[i]).Id.ToString().Equals(note.Key))
                        lstNotes.SetSelected(i, true);
        }

        private void frmDistributionMeterEditor_Load(object sender, EventArgs e)
        {
            LoadControls();
            LoadMeter();
            LoadImages();

            tabMain.SelectedTab = tabMainMeter;

            if (lstImages.Items.Count > 0)
                lstImages.SelectedIndex = 0;
            else
            {
                btnSearchImage.Enabled = true;
                pbxSelectedImage.Image = null;
            }
        }

        private void lstImages_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Delete)
                {
                    if (lstImages.SelectedIndex > -1)
                    {
                        Meter.Image = new EDistributionPoleImage();
                        LoadImages();

                        if (lstImages.Items.Count == 0)
                            btnSearchImage.Enabled = true;
                    }
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void LoadImages()
        {
            pbxSelectedImage.Image = null;

            lstImages.DataSource = null;
            lstImages.Items.Clear();

            if (Meter.Image != null && !String.IsNullOrEmpty(Meter.Image.FileName)) 
            {
                lstImages.Items.Add(Meter.Image);
                lstImages.DisplayMember = "Title";
            }

            if (lstImages.Items.Count > 0)
                btnSearchImage.Enabled = false;
        }

        private void lstImages_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (lstImages.SelectedIndex > -1)
                {
                    EDistributionPoleImage tmpImage = (EDistributionPoleImage)lstImages.SelectedItem;

                    viewImage(tmpImage);
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void viewImage(EDistributionPoleImage image)
        {
            FileInfo meterImage;

            if (!Pole.isProjectPole)
            {
                if (image.Id == Int32.MinValue)
                    meterImage = new FileInfo(image.FullName);
                else
                    meterImage = new FileInfo(DirHelper.GetImagesDirectory(m_OutboxBase.ConnectionString) + Path.DirectorySeparatorChar + image.FileName);
            }
            else
            {
                meterImage = new FileInfo(image.GetTemporaryFolder());
            }

            if (meterImage.Exists)
            {
                using (Stream s = File.OpenRead(meterImage.FullName))
                    pbxSelectedImage.Image = Image.FromStream(s);
            }
            else
                pbxSelectedImage.Image = null;
        }

        private void SaveMeter()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                EMeter actualMeter = Meter;

                if (lstImages.Items.Count > 0)
                    actualMeter.Image = lstImages.Items[0] as EDistributionPoleImage;
                else
                    actualMeter.Image = null;

                actualMeter.Comments = txtComments.Text.Trim();
                actualMeter.Number = txtNumber.Text.Trim();
                actualMeter.Latitude = position1.GetLatitude();
                actualMeter.Longitude = position1.GetLongitude();

                actualMeter.Notes.Clear();
                foreach (ENote note in lstNotes.SelectedItems)
                    actualMeter.Notes.Add(note);

                if (!Pole.isProjectPole)
                    LMeter.Update(m_OutboxBase.ConnectionString, Pole, actualMeter, true);
                else
                {
                    LMeter.UpdateMeter(m_OutboxBase.ConnectionString, Pole, actualMeter);

                    if (actualMeter.Image != null)
                        File.Copy(actualMeter.Image.FullName, actualMeter.Image.GetTemporaryFolder(), true);

                    Pole.Meters[Pole.Meters.IndexOf(actualMeter)] = actualMeter;
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveMeter();
            Close();
        }

        private void btnSearchImage_Click(object sender, EventArgs e)
        {
            SearchImage();
        }

        private void SearchImage()
        {
            try
            {
                OpenFileDialog _OpenFileDialog = new OpenFileDialog();
                DialogResult _DialogResult = _OpenFileDialog.ShowDialog();

                switch (_DialogResult)
                {
                    case DialogResult.OK:
                    case DialogResult.Yes:
                        FileInfo selectedFile = new FileInfo(_OpenFileDialog.FileName);

                        Meter.Image = new EDistributionPoleImage();
                        Meter.Image.ImageType = DistributionImageType.Meter;
                        Meter.Image.FullName = selectedFile.FullName;
                        Meter.Image.FileName = "Unsaved " + Path.GetFileName(selectedFile.FullName);

                        LoadImages();
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
